package org.example.review.service.impl;

import com.common.pojo.entity.OperationLog;
import org.example.review.constants.WorkStatus;
import org.example.review.dto.WorkDTO;
import org.example.review.mapper.OperationLogMapper;
import org.example.review.mapper.WorkMapper;
import org.example.review.service.WorkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.logging.Logger;

@Service
public class WorkServiceImpl implements WorkService {

    private static final Logger logger = Logger.getLogger(WorkServiceImpl.class.getName());

    @Autowired
    private WorkMapper workMapper;

    @Autowired
    private OperationLogMapper operationLogMapper;

    @Override
    public List<WorkDTO> getWorkList() {
        logger.info("开始获取工作列表");
        try {
            List<WorkDTO> workList = workMapper.selectWorkList();
            logger.info("获取工作列表成功，数量: " + workList.size());
            return workList;
        } catch (Exception e) {
            logger.severe("获取工作列表失败: " + e.getMessage());
            throw new RuntimeException("获取工作列表失败: " + e.getMessage());
        }
    }

    @Override
    public boolean approveWork(Integer id) {
        return approveWorkWithRemark(id, null);
    }

    /**
     * 审核通过工作项（带备注）
     * @param id 工作项ID
     * @param remark 操作备注
     * @return 操作结果
     */
    public boolean approveWorkWithRemark(Integer id, String remark) {
        logger.info("开始审核通过工作项，ID: " + id + ", 备注: " + remark);
        if (id == null || id <= 0) {
            logger.severe("工作项ID无效: " + id);
            return false;
        }

        try {
            // 获取当前状态
            Integer oldStatus = workMapper.selectCurrentStatus(id);
            if (oldStatus == null) {
                logger.warning("工作项不存在，ID: " + id);
                return false;
            }

            // 计算新状态
            Integer newStatus = calculateNewStatus(oldStatus, "approve");

            // 更新状态
            int affectedRows;
            if (remark != null && !remark.trim().isEmpty()) {
                affectedRows = workMapper.approveWorkWithRemark(id, remark);
            } else {
                affectedRows = workMapper.approveWork(id);
            }

            boolean success = affectedRows > 0;

            if (success) {
                // 记录操作日志
                recordOperationLog(id, oldStatus, newStatus, "approve", remark);
                logger.info("工作项审核通过成功，ID: " + id + ", 原状态: " + oldStatus + ", 新状态: " + newStatus + ", 备注: " + remark);
            } else {
                logger.warning("工作项审核通过失败，可能状态不允许或ID不存在，ID: " + id);
            }

            return success;
        } catch (Exception e) {
            logger.severe("审核通过工作项失败，ID: " + id + ", 错误: " + e.getMessage());
            throw new RuntimeException("审核通过工作项失败: " + e.getMessage());
        }
    }

    @Override
    public boolean rejectWork(Integer id, String reason) {
        logger.info("开始审核驳回工作项，ID: " + id + ", 原因: " + reason);
        if (id == null || id <= 0) {
            logger.severe("工作项ID无效: " + id);
            return false;
        }

        try {
            // 获取当前状态
            Integer oldStatus = workMapper.selectCurrentStatus(id);
            if (oldStatus == null) {
                logger.warning("工作项不存在，ID: " + id);
                return false;
            }

            // 计算新状态
            Integer newStatus = calculateNewStatus(oldStatus, "reject");

            // 更新状态
            int affectedRows;
            if (reason != null && !reason.trim().isEmpty()) {
                affectedRows = workMapper.rejectWorkWithRemark(id, reason);
            } else {
                affectedRows = workMapper.rejectWork(id);
            }

            boolean success = affectedRows > 0;

            if (success) {
                // 记录操作日志
                recordOperationLog(id, oldStatus, newStatus, "reject", reason);
                logger.info("工作项审核驳回成功，ID: " + id + ", 原状态: " + oldStatus + ", 新状态: " + newStatus + ", 原因: " + reason);
            } else {
                logger.warning("工作项审核驳回失败，可能状态不允许或ID不存在，ID: " + id);
            }

            return success;
        } catch (Exception e) {
            logger.severe("审核驳回工作项失败，ID: " + id + ", 错误: " + e.getMessage());
            throw new RuntimeException("审核驳回工作项失败: " + e.getMessage());
        }
    }

    /**
     * 计算新状态
     * @param oldStatus 当前状态
     * @param operation 操作类型：approve/reject
     * @return 新状态
     */
    private Integer calculateNewStatus(Integer oldStatus, String operation) {
        Integer newStatus;

        if ("approve".equals(operation)) {
            // 审核通过的状态转换 (整合了首次通过和驳回后重新通过)
            switch (oldStatus) {
                case WorkStatus.TRAVEL_REVIEWING:     // 2 -> 4 (首次通过)
                case WorkStatus.ADVANCE_REVIEWING:    // 3 -> 4 (首次通过)
                case WorkStatus.TRAVEL_REJECTED:      // 1 -> 4 (驳回后修改为通过)
                    newStatus = WorkStatus.ADVANCE_APPROVED;
                    break;

                case WorkStatus.REIMBURSE_REVIEWING:  // 6 -> 7 (首次通过)
                case WorkStatus.PAYMENT_REVIEWING:    // 7 -> 8 (首次通过)
                case WorkStatus.REIMBURSE_REJECTED:   // 5 -> 8 (驳回后修改为通过)
                    newStatus = WorkStatus.PAYMENT_REVIEWING; // 或者直接 WorkStatus.COMPLETED，取决于业务
                    break;

                case WorkStatus.ADVANCE_APPROVED:      // 4 -> 4 (已通过，再次通过，状态不变)
                case WorkStatus.COMPLETED:             // 8 -> 8 (已完成，再次通过，状态不变)
                    newStatus = oldStatus;
                    break;

                default: // 其他未知状态，不做修改
                    newStatus = oldStatus;
                    break;
            }

        } else if ("reject".equals(operation)) {
            // 审核驳回的状态转换 (整合了首次驳回和通过后修改为驳回)
            switch (oldStatus) {
                // 差旅/预支阶段的驳回 (无论是首次还是被通过后驳回)
                case WorkStatus.TRAVEL_REVIEWING:     // 2 -> 1 (首次驳回)
                case WorkStatus.ADVANCE_REVIEWING:    // 3 -> 1 (首次驳回)
                case WorkStatus.ADVANCE_APPROVED:     // 4 -> 1 (通过后修改为驳回)
                    newStatus = WorkStatus.TRAVEL_REJECTED;
                    break;

                // 报销/支付阶段的驳回 (无论是首次还是进行中驳回)
                case WorkStatus.REIMBURSE_REVIEWING:  // 6 -> 5 (首次驳回)
                case WorkStatus.PAYMENT_REVIEWING:    // 7 -> 5 (首次驳回)
                case WorkStatus.COMPLETED:             // 8 -> 5 (完成后修改为驳回，业务上需谨慎)
                    newStatus = WorkStatus.REIMBURSE_REJECTED;
                    break;

                case WorkStatus.TRAVEL_REJECTED:      // 1 -> 1 (已驳回，再次驳回，状态不变)
                case WorkStatus.REIMBURSE_REJECTED:   // 5 -> 5 (已驳回，再次驳回，状态不变)
                    newStatus = oldStatus;
                    break;

                default: // 其他未知状态，不做修改
                    newStatus = oldStatus;
                    break;
            }
        } else {
            // 非法操作
            throw new IllegalArgumentException("未知的审批操作: " + operation);
        }

// 返回计算出的新状态，用于后续的数据库更新
        return newStatus;
    }

    /**
     * 记录操作日志
     * @param applyId 申请ID
     * @param oldStatus 原状态
     * @param newStatus 新状态
     * @param operationType 操作类型
     * @param remark 备注
     */
    private void recordOperationLog(Integer applyId, Integer oldStatus, Integer newStatus,
                                  String operationType, String remark) {
        try {
            OperationLog operationLog = new OperationLog();
            operationLog.setApplyId(applyId);

            operationLog.setRemark(remark);

        } catch (Exception e) {
            logger.severe("记录操作日志失败，申请ID: " + applyId + ", 错误: " + e.getMessage());
            // 不抛出异常，避免影响主业务流程
        }
    }

    /**
     * 获取工作项当前状态
     * @param id 工作项ID
     * @return 当前状态
     */
    @Override
    public Integer getWorkItemStatus(Integer id) {
        logger.info("获取工作项状态，ID: " + id);
        if (id == null || id <= 0) {
            logger.warning("工作项ID无效: " + id);
            return null;
        }

        try {
            Integer status = workMapper.selectCurrentStatus(id);
            logger.info("获取工作项状态成功，ID: " + id + ", 状态: " + status);
            return status;
        } catch (Exception e) {
            logger.severe("获取工作项状态失败，ID: " + id + ", 错误: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }
}